package yunquan.wang.modules.base.web;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import yunquan.wang.base.config.AppConfig;
import yunquan.wang.base.service.BaseService;
import yunquan.wang.base.utils.DateTimeUtils;
import yunquan.wang.base.web.BaseController;
import yunquan.wang.modules.base.entity.BackupDatabase;
import yunquan.wang.modules.base.entity.SystemConfig;
import yunquan.wang.modules.base.service.BackupDatabaseService;

@Controller
@RequestMapping("/core/backupdata")
public class DatabaseBakController extends BaseController<BackupDatabase> {
	@Resource
	private BackupDatabaseService backupDatabaseService;

	@Override
	public BaseService<BackupDatabase> getService() {
		return backupDatabaseService;
	}

	@RequestMapping(value = "/list.do")
	public ModelAndView list() {
		return baseList();
	}

	@RequestMapping(value = "/save.do")
	public ModelAndView save(@Valid BackupDatabase entity,
			BindingResult bindingResult) {
		ModelAndView mv = new ModelAndView("redirect:list.do");
		backupDatabaseService.backUpdataAll(entity.getBackName());
		return mv;
	}

	@RequestMapping(value = "/delete.do")
	public ModelAndView delete() {
		return baseDelete();
	}

	@RequestMapping(value = "/input.do")
	public ModelAndView input() {
		return baseInput();
	}

	@RequestMapping(value = "/restore.do")
	public ModelAndView restore(String id) {
		backupDatabaseService.restoreData(id);
		return baseList();
	}

	@RequestMapping(value = "/upload.do")
	public ModelAndView upload() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	@RequestMapping(value = "/view.do")
	public ModelAndView view(String id) {
		return baseView();
	}

	@RequestMapping(value = "/updata.do")
	public ModelAndView updata(MultipartFile upFile, String bakName) {
		String dateTime = DateTimeUtils
				.getCurrentDateString(DateTimeUtils.SSFORMARTSTRING);
		File backPath = new File(AppConfig.getBackDbFilePath());
		if (!backPath.exists()) {
			backPath.mkdir();
		}
		String filepath = AppConfig.getBackDbFilePath() + File.separator
				+ dateTime + ".zip";

		File des = new File(filepath);
		try {
			upFile.transferTo(des);

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Long size = des.length() / 1024;
		BackupDatabase bak = new BackupDatabase();
		bak.setBackName(bakName);
		bak.setFilesize(size.intValue());
		bak.setSuccess(true);
		bak.setFileName(dateTime + ".zip");
		backupDatabaseService.save(bak);
		ModelAndView mv = new ModelAndView("redirect:list.do");
		return mv;
	}
}
